package cn.com.fattiger.framework.cms.admin.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import cn.com.fattiger.framework.cms.admin.common.model.User;

/**
 * Created by Administrator on 2015/11/30.
 */
@Component
public class LoginFilter implements Filter {

    private List<String> publicPermission = new ArrayList<String>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // init common reqest.
        publicPermission.add("frameCtl.do");
        publicPermission.add("logout.do");
        publicPermission.add("tpl_welcome.do");
        publicPermission.add("gateway.do");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String uri = request.getRequestURI();
        String action = uri.substring(uri.lastIndexOf("/") + 1, uri.length());
        System.err.println("****************** action:" + action);

        // 根据请求地址进行是否需要登录校验,初次访问浏览器会在地址后面加上;jessionid=xxx信息,所以不能通过getRequestURI截取请求路径
        // 根据getServletPath可以正确截取

        User _user_ = (User) request.getSession().getAttribute("__USER__");
        if (!"login.do".equalsIgnoreCase(action) && null != _user_) {

            List<String> permissions = (List<String>) request.getSession().getAttribute("__PERMISSION__");
            permissions.addAll(publicPermission);

            // 暂时不加入三级功能权限校验，未具备，有风险：知道请求地址可直接访问
            // 模块(m)--->资源(r)---->权限(p)
            /*
            if (_user_.getType() != -1 && !permissions.contains(action)) {
                servletResponse.getWriter().write("401:Permission Denied!");
                return;
            }
            */
            filterChain.doFilter(servletRequest, servletResponse);

        } else if ("login.do".equalsIgnoreCase(action)||"idCheck.do".equals(action)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendRedirect("login.do");
        }
    }

    @Override
    public void destroy() {

    }
}
